﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.Xml.Serialization;
using System.Globalization;
using HealthCenter.MECReportService;
using System.ServiceModel;
using System.ServiceModel.Channels;
using HealthCenter.ciic;
using HealthCenter.MecreportProxyService;

namespace HealthCenter
{
    public partial class ReportEditorForm : Form
    {
        private List<ApparatusReport> reports;
        public ReportEditorForm()
        {
            InitializeComponent();
        }

        private void BtnUploadClick(object sender, EventArgs e)
        {
            List<ApparatusReport> reports = GetReportsFromXml();

            if (reports == null || reports.Count <= 0)
            {
                MessageBox.Show("请先选择要上传的数据点击确定后再点击上传！");
                return;
            }

            //LoginForm form = new LoginForm();
            //DialogResult dr = form.ShowDialog();
            //if (form.LoginSucceed)
            //{
                foreach (ApparatusReport report in reports)
                {
                    if (!report.Uploaded)
                    {
                        string msg = Upload4(report);
                        MessageBox.Show(msg);
                        //if (succeed)
                        //{
                            report.Uploaded = true;
                        //}
                    }
                }
            //}

            SaveReportsToXml(reports);

            //List<string> ids = GetSelectedItemIds();
            //if (ids != null)
            //{
            //    foreach (string id in ids)
            //    {
            //        Upload(id);
            //    }
            //}
            //DataGridViewSelectedRowCollection coll = dataGridView2.SelectedRows;
            //int count = coll.Count;
            //if (count > 0)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    for (int i = 0; i < coll.Count; i++)
            //    {
            //        DataGridViewRow row = coll[i];
            //        string id = (string)row.Cells[0].Value;
            //        if (i != 0)
            //        {
            //            sb.Append(",");
            //        }
            //        sb.Append(id);
            //    }
            //    DialogResult result = MessageBox.Show("确定要上传" + sb.ToString() + "号数据吗？", 
            //        "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            //    if (result == DialogResult.Yes)
            //    {
            //        MessageBox.Show(sb.ToString() + "上传成功！");
            //    }
                
            //}
            //else
            //{
            //    MessageBox.Show("请选择要上传的数据！");
            //}
        }

        private List<string> GetSelectedItemIds()
        {
            List<string> ids = null;

            DataGridViewSelectedRowCollection coll = dataGridView2.SelectedRows;
            int count = coll.Count;
            if (count > 0)
            {
                ids = new List<string>();
                for (int i = 0; i < coll.Count; i++)
                {
                    DataGridViewRow row = coll[i];
                    string id = (string)row.Cells[1].Value;
                    ids.Add(id);
                }
            }
            return ids;
        }

        private void ReportEditorForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if(NeedTagAsUpload())
            {
                DialogResult ds = MessageBox.Show("在您最近一次的操作中，你有数据没有标记为上传，在进行下一次查询之前，您必须先将上一次操作的数据设置为已上传，才可以进行下一步的操作你需要设置为已上传吗？",
                    "注意",MessageBoxButtons.YesNo);
                if (ds == DialogResult.Yes)
                {
                    TagAsUploaded();
                }
                else
                {
                    return;
                }
            }
            this.Cursor = Cursors.WaitCursor;
            reports = CiicHelper.FindReports(dtpStart.Value, dtpEnd.Value, false, null);
            dataGridView2.DataSource = reports;
            this.Cursor = Cursors.Default;
        }

        private bool Upload(ApparatusReport report)
        {
            WebHeaderCollection c = new WebHeaderCollection(); ;
            GlobalInfo.Client.Headers = c;
            c.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            c.Add(HttpRequestHeader.Referer, "http://www.scars.org.cn/FPWEB/Report/ReportEdit/RP_Mec_Edit.aspx");
            c.Add(HttpRequestHeader.AcceptLanguage, "zh-cn");
            c.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; InfoPath.1; .NET CLR 2.0.50727; CIBA; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)");
            c.Add(HttpRequestHeader.Pragma, "no-cache");
            c.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            c.Add(HttpRequestHeader.ContentEncoding, "charset=utf-8");
            c.Add(HttpRequestHeader.Accept, "*/*");
            c.Add(HttpRequestHeader.Cookie, GlobalInfo.cookie);
            c.Add(HttpRequestHeader.KeepAlive, "true");

            //GlobalInfo.Client.DownloadData("http://www.scars.org.cn/FPWEB/Report/ReportEdit/RP_Mec_Edit.aspx");
            //string cookie = GlobalInfo.Client.ResponseHeaders["Set-Cookie"];
            //c.Add(HttpRequestHeader.Cookie, cookie);
            string url = "http://www.scars.org.cn/FPWEB/WebService/MECReport.asmx/MecInsert";
            NameValueCollection form = new NameValueCollection();
            form.Add("Mec_sex", "女");
            form.Add("Mec_hopeill", "宫内节育器用于避孕");
            form.Add("Mec_location", "医院");
            form.Add("Mec_result", "取出器械");
            form.Add("Mec_sortname", "IUD");
            form.Add("Mec_operater", "专业人员");
            form.Add("Mec_eventdisposething", "处理");
            form.Add("Mec_reportermetier", "医生");
            form.Add("Mec_rpsource", "使用单位");
            form.Add("Initiative", "N");
            form.Add("Mec_property", "一般");
            form.Add("Mec_rpdate", DateTime.Today.ToShortDateString());
            form.Add("Mec_sufferer", report.A1);
            form.Add("Mec_reportman", "");
            form.Add("Mec_eventbehave", "*");
            form.Add("Mec_eventdate", report.C17);
            form.Add("Mec_merchandisename", "*" + report.C11);
            form.Add("Mec_unitcontact", "上海市柳州路118号");
            form.Add("Mec_postcode", "200235");
            form.Add("Mec_telphone", "64841237");
            form.Add("Mec_IDCard", report.A0);
            form.Add("Mec_womancode", "");
            form.Add("Mec_age", report.A2);
            form.Add("Mec_eventdescription1", report.B91);
            form.Add("Mec_eventdescription2", report.B92);
            form.Add("Mec_eventdescription3", report.B93);
            form.Add("Mec_eventdescription4", report.B94);
            form.Add("Mec_eventdescription5", report.B95);
            form.Add("Mec_eventdescription6", report.B96);
            form.Add("Mec_eventdescription7", report.B97);
            form.Add("Mec_registercode", "");
            form.Add("Mec_producefactory", "");
            form.Add("Mec_produceaddress", "");
            form.Add("Mec_producetelphone", "");
            form.Add("Mec_deathdate", "");
            form.Add("Mec_productcode", "");
            form.Add("Mec_productbatchcode", "");
            form.Add("Mec_spec", "");
            form.Add("Mec_finishdate", FormatTime(report.C16, "1900-1-1"));
            form.Add("Mec_stopdate", FormatTime(report.C17, DateTime.Now.ToShortDateString()));
            form.Add("Mec_startdate", FormatTime(report.C18, DateTime.Now.ToShortDateString()));
            form.Add("Mec_eventhappewhy", report.C19);
            form.Add("Mec_eventdisposecontent", "");
            form.Add("Mec_provinceideashow", "");
            form.Add("Mec_countryideashow", "");
            form.Add("Mec_department", "");
            form.Add("Mec_unitname", "徐汇区妇幼保健所");
            form.Add("Mec_israndomfind", "0");
            form.Add("Mec_eventrpstate", "");

            byte[] response = GlobalInfo.Client.UploadValues(url, form);

            string ret = Encoding.UTF8.GetString(response);
            Console.WriteLine(ret);
            return true;
        }

        private bool Upload2(ApparatusReport report)
        {
            //MECReportSoapClient client = new MECReportSoapClient("MECReportSoap");

            RXD_NationalSoapClient client = new RXD_NationalSoapClient();

            //client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            //using (new OperationContextScope(client.InnerChannel)) 
            //{
            //    HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
            //    requestProperty.Headers.Add("Cookie", GlobalInfo.cookie);
            //    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;

                string s = client.MecInsert(GlobalInfo.cookie,"女", "使用单位", "宫内节育器用于避孕", "医院",
                    "取出器械", "IUD", "N", "专业人员", "处理", "医生",
                    DateTime.Today.ToShortDateString(), "", report.A1, "",
                    report.A0, "", report.A2, "*", report.C17, report.B91,
                    report.B92, report.B93, report.B94, report.B95, report.B96,
                    report.B97, "*" + report.C11, "", "", "", "", "", "", "", "",
                    FormatTime(report.C16, "1900-1-1"), FormatTime(report.C17,
                    DateTime.Now.ToShortDateString()), FormatTime(report.C18,
                    DateTime.Now.ToShortDateString()), report.C19, "", "", "",
                    "0", "", "64841237", "徐汇区妇幼保健所", "上海市柳州路118号",
                    "200235", "一般");
                Console.WriteLine(s);
            //}
            return true;
        }

        private bool Upload3(ApparatusReport report)
        {

            WebProxy wp = new WebProxy("192.168.0.12",808);
            wp.Credentials = CredentialCache.DefaultCredentials;
            WebRequest.DefaultWebProxy = wp;

            //BasicHttpBinding bhb = new BasicHttpBinding();
            //bhb.UseDefaultWebProxy = false;
            //bhb.ProxyAddress = null;

            EndpointAddress ea = new EndpointAddress("http://www.scars.org.cn/FPWEB/WebService/MECReport.asmx");

            ServiceReference1.MECReportSoapClient client = new ServiceReference1.MECReportSoapClient("MECReportSoap1");


            //bhb.AllowCookies = true;

            using (new OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
                requestProperty.Headers.Add("Cookie", GlobalInfo.cookie);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;

                string s = client.MecInsert("女", "使用单位", "宫内节育器用于避孕", "医院",
                    "取出器械", "IUD", "N", "专业人员", "处理", "医生",
                    DateTime.Today.ToShortDateString(), "", report.A1, "",
                    report.A0, "", report.A2, "*", report.C17, report.B91,
                    report.B92, report.B93, report.B94, report.B95, report.B96,
                    report.B97, "*" + report.C11, "", "", "", "", "", "", "", "",
                    FormatTime(report.C16, "1900-1-1"), FormatTime(report.C17,
                    DateTime.Now.ToShortDateString()), FormatTime(report.C18,
                    DateTime.Now.ToShortDateString()), report.C19, "", "", "",
                    "0", "", "64841237", "徐汇区妇幼保健所", "上海市柳州路118号",
                    "200235", "一般");
                Console.WriteLine(s);
            }
            return true;
        }

        private ApparatusReport GetReportById(string id)
        {
            if (reports != null)
            {
                foreach (ApparatusReport report in reports)
                {
                    if (report.ID == id)
                    {
                        return report;
                    }
                }
            }
            return null;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            TagAsUploaded();
        }

        private void TagAsUploaded()
        {
            List<ApparatusReport> reports = GetReportsFromXml();
            if (reports != null)
            {
                foreach (ApparatusReport report in reports)
                {
                    if (report.Uploaded)
                    {
                        CiicHelper.UpdateReportAsReportedById(report.ID);
                    }
                }
            }
            File.Delete(GlobalInfo.ReportsXmlPath);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestForm t = new TestForm();
            t.Show();
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            List<string> ids = GetSelectedItemIds();
            List<ApparatusReport> selectedReports = new List<ApparatusReport>();
            if (ids != null)
            {
                foreach (string id in ids)
                {
                    foreach (ApparatusReport report in reports)
                    {
                        if (report.ID == id)
                        {
                            selectedReports.Add(report);
                        }
                    }
                }
            }
            if(selectedReports.Count > 0)
                SaveReportsToXml(selectedReports);
        }

        private List<ApparatusReport> GetReportsFromXml()
        {
            List<ApparatusReport> reports = null;
            if(File.Exists(GlobalInfo.ReportsXmlPath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<ApparatusReport>));

                TextReader reader = new StreamReader(GlobalInfo.ReportsXmlPath);
                reports = (List<ApparatusReport>)serializer.Deserialize(reader);
                reader.Close();
            }
            return reports;
        }

        private void SaveReportsToXml(List<ApparatusReport> reports)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<ApparatusReport>));
            TextWriter writer = new StreamWriter(GlobalInfo.ReportsXmlPath);
            serializer.Serialize(writer, reports);
            writer.Close();
        }

        private bool NeedTagAsUpload()
        {
            List<ApparatusReport> reports = GetReportsFromXml();
            if (reports != null)
            {
                foreach (ApparatusReport report in reports)
                {
                    if (report.Uploaded)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private string FormatTime(string value, string defaultValue)
        {
            try
            {
                DateTime dt = DateTime.Parse(value);
                return dt.ToShortDateString();
            }
            catch(FormatException)
            {
            }
            return defaultValue;
        }

        private string Upload4(ApparatusReport report)
        {
            MecReportProxyServiceSoapClient client = new MecReportProxyServiceSoapClient("MecReportProxyServiceSoap", GlobalInfo.ProxyServiceUrl);

            string s = client.MecInsert(GlobalInfo.cookie, "女", "使用单位", "宫内节育器用于避孕", "医院",
                "取出器械", "IUD", "N", "专业人员", "处理", "医生",
                DateTime.Today.ToShortDateString(), "", report.A1, "",
                report.A0, "", report.A2, "*", report.C17, report.B91,
                report.B92, report.B93, report.B94, report.B95, report.B96,
                report.B97, "*" + report.C11, "", "", "", "", "", "", "", "",
                FormatTime(report.C16, "1900-1-1"), FormatTime(report.C17,
                DateTime.Now.ToShortDateString()), FormatTime(report.C18,
                DateTime.Now.ToShortDateString()), report.C19, "", "", "",
                "0", "", "64841237", "徐汇区妇幼保健所", "上海市柳州路118号",
                "200235", "一般");
            return s;
        }

        private void ReportEditorForm_Shown(object sender, EventArgs e)
        {
            dataGridView2.DataSource = GetReportsFromXml();
        }
    }
}
